package com.example.demo.pay;

import com.example.demo.common.IdGenerator;
import com.example.demo.repo.RepertoryCache;
import com.example.demo.repo.RepertoryRepo;
import com.example.demo.repo.Repo;
import com.example.demo.repo.model.Bill;
import com.example.demo.repo.model.Order;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;

import static com.example.demo.repo.model.Order.OrderStatus.not_pay;

@RestController
@RequestMapping("/pay")
public class PayController {

    // 支付
    @PostMapping("/pay")
    public Order.OrderStatus pay(@RequestBody Bill bill) {

        Optional<Order> orderOptional = repo.getOrder(bill.getOrderId());
        if (!orderOptional.isPresent()) throw new RuntimeException("订单不存在");

        Order order = orderOptional.get();

        if (order.getOrderStatus() != not_pay) {
            // 非未支付状态，不能重复支付
            // 根据状态返回相应提示
            throw new RuntimeException(order.getOrderStatus().name());
        }

        // 支付验证
        // 支付金额验证、实际支付验证...

        // 支付成功 or 支付失败...
        if (true) { // 成功
            order.setOrderStatus(Order.OrderStatus.payed);
            order.setUpdateTime(new Date().getTime());
            order.setMsg("支付成功：" + (order.getUpdateTime() - order.getCreateTime()));
            repo.putOrder(order);
        } else { // 失败
            order.setOrderStatus(Order.OrderStatus.pay_fail);
            order.setUpdateTime(new Date().getTime());
            order.setMsg("支付失败，请重新支付：" + (order.getUpdateTime() - order.getCreateTime()));
            repo.putOrder(order);

            // 库存恢复
            repertoryRepo.takeOut(order.getProductId(), -1 * order.getNumbers());
            repertoryCache.takeOut(order.getProductId(), -1 * order.getNumbers());
        }

        // 更新账单
        bill.setBillId(idGenerator.genId());
        bill.setCreateTime(new Date().getTime());
        repo.putBill(bill);

        return order.getOrderStatus();
    }

    private IdGenerator idGenerator;
    private Repo repo;
    private RepertoryRepo repertoryRepo;
    private RepertoryCache repertoryCache;

    public PayController(IdGenerator idGenerator, Repo repo,
                         RepertoryRepo repertoryRepo, RepertoryCache repertoryCache) {
        this.idGenerator = idGenerator;
        this.repo = repo;
        this.repertoryRepo = repertoryRepo;
        this.repertoryCache = repertoryCache;
    }

}
